package com.netease.nie.service;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netease.nie.base.utils.CopyUtils;
import com.netease.nie.config.AdminAreaProperties;
import com.netease.nie.dao.OrdersAddressDao;
import com.netease.nie.dto.OrdersAddressDto;
import com.netease.nie.model.OrdersAddress;

@Service
public class OrdersAddressServiceImpl implements OrdersAddressService {

	@Autowired
	private OrdersAddressDao ordersAddressDao;
	
	@Autowired
	private AdminAreaProperties adminAreaProperties;
	
	public OrdersAddressDto queryOrdersAddressByOrdersId(long orderId) {
		OrdersAddress ordersAddress = ordersAddressDao.queryOrdersAddressByOrdersId(orderId);
		if (ordersAddress == null)
			return null;
		
		OrdersAddressDto ordersAddressDto = new OrdersAddressDto();
		CopyUtils.copy(ordersAddressDto, ordersAddress);
		replaceChooseAddress(ordersAddressDto);
		
		return ordersAddressDto;
	}

	public void replaceChooseAddress(OrdersAddressDto ordersAddressDto) {
		String chooseAddr = ordersAddressDto.getChooseAddr();
		String replaceAddr;
		Map<Integer, String> adminAreaMap = adminAreaProperties.getAdminAreaMap();
		if (StringUtils.isNotBlank(chooseAddr)) {
			String[] addrs = chooseAddr.split("-");
			Integer provinceCode = Integer.parseInt(addrs[0]);
			replaceAddr = adminAreaMap.get(provinceCode);
			
			if (addrs.length > 1) {
				Integer cityCode = Integer.parseInt(addrs[1]);				
				replaceAddr = replaceAddr + "-" + adminAreaMap.get(cityCode);
			}
			ordersAddressDto.setChooseAddr(replaceAddr);
		}
	}
}
